package com.yunshipei.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.SortModel;

import java.util.List;

import io.rong.app.utils.StringUtilSub;

public class Search_sortAdapter extends BaseAdapter implements SectionIndexer {
    private List<SortModel> list = null;
    private Context mContext;
    BitmapDrawable drawable;
    private ListView mListView;

    public Search_sortAdapter(Context mContext, List<SortModel> list) {
        this.mContext = mContext;
        this.list = list;
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param list
     */
    public void updateListView(List<SortModel> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public int getCount() {
        return this.list.size();
    }

    public Object getItem(int position) {
        return list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View view, ViewGroup parent) {
        if (mListView == null) {
            mListView = (ListView) parent;
        }
        ViewHolder viewHolder = null;
        final SortModel mContent = list.get(position);
        int section = getSectionForPosition(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_sort_listview, null);
            viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);    //字母
            viewHolder.nameTV = (TextView) view.findViewById(R.id.name);        //姓名
            viewHolder.positionTV = (TextView) view.findViewById(R.id.position);            //职位
            viewHolder.avatar = (ImageView) view.findViewById(R.id.avatar);            //头像
            viewHolder.avatarText = (TextView) view.findViewById(R.id.avatarText);

        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
        if (position == getPositionForSection(section)) {
            viewHolder.tvLetter.setVisibility(View.VISIBLE);
            viewHolder.tvLetter.setText(mContent.getSortLetters());
        } else {
            viewHolder.tvLetter.setVisibility(View.GONE);
        }
        viewHolder.nameTV.setText(substringFixedStr(this.list.get(position).getUserInfo().getName(), 8));
        String posValue = this.list.get(position).getUserInfo().getPosition();
        viewHolder.positionTV.setText(TextUtils.isEmpty(posValue) || "null".equals(posValue) ? "" : posValue);
        if (StringUtilSub.isChinese(this.list.get(position).getUserInfo().getName())) {
            viewHolder.avatarText.setText(getEndword(this.list.get(position).getUserInfo().getName()));
        } else {
            viewHolder.avatarText.setText(this.list.get(position).getUserInfo().getName().substring(0, 1).toString().toUpperCase());
        }
        viewHolder.avatar.setImageResource(MyListViewAdapter.person_logos[position % MyListViewAdapter.person_logos.length]);
        view.setTag(viewHolder);
        String key1 = this.list.get(position).getUserInfo().getAvatar();
        if (!"notimage".equals(key1) && key1 != null) {
            viewHolder.avatar.setTag(this.list.get(position).getUserInfo().getUuid());
            viewHolder.avatarText.setVisibility(View.GONE);
        } else {
            viewHolder.avatarText.setVisibility(view.VISIBLE);
        }
        if (drawable != null) {
            //将头像设置到listview上去
            viewHolder.avatar.setImageDrawable(drawable);
        } else {
            if (!"notimage".equals(key1) && key1 != null) {
//                BitmapWorkerTask task = new BitmapWorkerTask(viewHolder.avatar, viewHolder.avatarText);
//                task.execute(this.list.get(position).getUserInfo().getAvatar(), this.list.get(position).getUserInfo().getUuid());

                String imgUrl = list.get(position).getUserInfo().getAvatar();
                Glide.with((Activity) mContext).load(imgUrl).into(viewHolder.avatar);
            }
        }
        return view;

    }

    final static class ViewHolder {
        TextView tvLetter, avatarText;//字母
        TextView nameTV, positionTV;
        ImageView avatar;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return list.get(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = list.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 提取英文的首字母，非英文字母用#代替。
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        String sortStr = str.trim().substring(0, 1).toUpperCase();
        // 正则表达式，判断首字母是否是英文字母
        if (sortStr.matches("[A-Z]")) {
            return sortStr;
        } else {
            return "#";
        }
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    /**
     * 截取字符串
     *
     * @param originalStr
     * @return
     */
    public static String getEndword(String originalStr) {
        String endWord;
        if (originalStr != null) {
            int len = originalStr.length();
            endWord = originalStr.substring(len - 1, len);
            return endWord;
        } else {
            return "";
        }
    }

    /**
     * @param originalStr 被截取字符串
     * @param subLen      字符串长度标准
     * @return
     */
    private String substringFixedStr(String originalStr, int subLen) {
        String str = null;
        if (originalStr == null) {
            return str = "未知";
        } else if (originalStr.equals("") || originalStr.equals("null")) {
            str = "未知";
        } else {
            int strLen = originalStr.length();
            if (strLen > subLen) {
                str = originalStr.substring(0, subLen);
            } else {
                return originalStr;
            }
        }
        return str;
    }
}

